// index.js
import { wxPromisify, throttle } from '../../utils/util'
import { conf, env } from '../../config.js'
import data from '../../data.js'
// 获取应用实例
const appData = getApp().globalData

Page({
  data: {
    showDialog: false,
    canvas: {},
    ctx: null,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    currentIndex: 0,
    logoList: [],
    openSetting: false,
    height: appData.height,
    // logo移动旋转相关属性
    logoIsActive: true,
    avatar: null, // 头像和logo的本地链接
    logo: null,
    icon: null,
    imgW: 0,
    imgH: 0,
    cvsW: 0,
    cvsH: 0,
    beginX: 0,
    beginY: 0,
    LT: {},
    isDown: false,
    moveAble: false,
    rotateAble: false,
    rotate_radian: 0,
    scale: 1,
    PO: {},
    rotateR: 15,
    pyqIcon: `${conf.staticDomain}time-line-icon.png?v=${appData.imgVersion}`,
    wechatIcon: `${conf.staticDomain}wechat-icon.png?v=${appData.imgVersion}`
  },
  swiperChange: function (e) {
    this.setData({
      currentIndex: e.detail.current
    })
    this.setData({
      avatar: '',
      logo: '',
      icon: '',
      degree: 0,
      scale: 1
    })
    this.initCanvasFisrt()
  },
  bindGetUserInfo(e) {
    const that = this
    if (e.detail.userInfo) {
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
      wx.setStorageSync('userInfo', JSON.stringify(e.detail.userInfo));
      that.initCanvasFisrt()
    } else { // 拒绝授权
      wx.showToast({
        title: '授权失败',
        icon: 'none'
      })
    }
  },
  calcStartPoint(obj) {
    const { canvas } = this.data
    let x, y
    switch (obj.startPoint) {
      case 'right-bottom':
        x = canvas.width - obj.w - obj.x
        y = canvas.height - obj.h - obj.y
        break;
      case 'right-top':
        x = canvas.width - obj.w - obj.x
        y = obj.y
        break;
      case 'left-bottom':
        x = obj.x
        y = canvas.height - obj.h - obj.y
        break;
      case 'left-top':
        x = obj.x
        y = obj.y
        break;
      case 'top-center':
        x = (canvas.width - obj.w) / 2
        y = obj.y
        break;
      case 'bottom-center':
        x = (canvas.width - obj.w) / 2
        y = canvas.height - obj.h - obj.y
        break;
      case 'left-center':
        x = obj.x
        y = (canvas.height - obj.h) / 2
        break;
      case 'right-center':
        x = canvas.width - obj.w - obj.x
        y = (canvas.height - obj.h) / 2
        break;
      default:
    }
    return { x, y, w: obj.w, h: obj.h }
  },
  // 画一个圆角矩形，并放入图片裁剪 
  storeAvatar(ctx, img, bg_x, bg_y, bg_w, bg_h) { // x, y是图片所在矩形左上角的坐标
    // 头像比背景预留10px的宽度
    let bg_r = 12, avt_x = bg_x + 10, avt_y = bg_y + 10, avt_w = bg_w - 20, avt_h = bg_h - 20;
    // 先画一个白色的矩形
    ctx.rect(0, 0, bg_w, bg_h)
    ctx.fillStyle = "white";
    ctx.fill();
    ctx.save() // 保存到当前画布状态
    ctx.beginPath()
    ctx.arc(avt_x + bg_r, avt_y + bg_r, bg_r, Math.PI, Math.PI * 1.5)
    ctx.arc(avt_x + avt_w - bg_r, avt_y + bg_r, bg_r, Math.PI * 1.5, Math.PI * 2)
    ctx.arc(avt_x + avt_w - bg_r, avt_y + avt_h - bg_r, bg_r, 0, Math.PI * 0.5)
    ctx.arc(avt_x + bg_r, avt_y + avt_h - bg_r, bg_r, Math.PI * 0.5, Math.PI)
    ctx.clip()
    ctx.drawImage(img, avt_x, avt_y, avt_w, avt_h);
    ctx.restore();
  },
  saveImg() {
    const that = this
    const {
      canvas,
      openSetting,
      logoIsActive
    } = this.data;
    let _this = this;
    if (logoIsActive) {
      this.saveLogo()
    }
    if (openSetting) {
      wx.openSetting({
        success({ authSetting }) {
          if (authSetting['scope.writePhotosAlbum']) {
            _this.setData({
              openSetting: false
            })
          }
        }
      });
    } else {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        x: 0,
        y: 0,
        width: canvas.width,
        height: canvas.height,
        quality: 1,
        success: (res) => {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success() {
              that.setData({
                showDialog: true
              })
            },
            fail(err) {
              _this.setData({
                openSetting: true
              })
            }
          })
        },
        fail(err) {
          console.info(err)
        }
      }, this)
    }
  },
  getHighLevelAvatar(url) {
    if (url) {
      return url.replace(/\/132$/g, '/0')
    }
    return ''
  },
  initCanvasFisrt() {
    const that = this
    const { logoList, currentIndex, userInfo, ctx, cvsW, cvsH } = this.data
    const item = logoList[currentIndex]
    const wxGetImageInfo = wxPromisify(wx.getImageInfo);
    wx.showLoading({ title: '图片加载中', mask: true });
    Promise.all([
      wxGetImageInfo({
        src: item.url
      }),
      wxGetImageInfo({
        src: this.getHighLevelAvatar(userInfo.avatarUrl)
      }),
      wxGetImageInfo({
        src: `${conf.staticDomain}rotate_icon.png`
      })
    ]).then((res) => {
      var lp = that.calcStartPoint(item)
      that.setData({
        logo: res[0].path,
        avatar: res[1].path,
        icon: res[2].path,
        LT: {
          x: lp.x,
          y: lp.y
        },
        imgH: lp.h,
        imgW: lp.w,
        logoIsActive: true
      })
      const PO = {
        x: lp.x + lp.w / 2, y: lp.y + lp.h / 2
      }
      that.setData({
        PO
      }, () => {
        ctx.clearRect(-cvsW, -cvsH, 2 * cvsW, 2 * cvsH);
        // ctx.drawImage(res[1].path, 0, 0, cvsW, cvsH);
        that.storeAvatar(ctx, res[1].path, 0, 0, cvsW, cvsH)
        ctx.translate(PO.x, PO.y);//载入时将canvas坐标系原点移到图片中心点上
        wx.hideLoading();
        that.onDraw(true)
      })
    }, (err) => {
      wx.hideLoading();
      console.info(err)
    })
    this.setData({
      isFirst: false
    })
  },
  onDraw(addBorder = false, cb) {
    const { ctx, logo, icon, imgW, imgH, rotateR, scale } = this.data
    var width = imgW, height = imgH;
    if (scale !== 1) {
      width = width * scale
      height = height * scale
    }
    // 画logo
    ctx.drawImage(logo, -width / 2, -height / 2, width, height);
    if (addBorder) {
      ctx.beginPath();
      ctx.lineWidth = "1";
      ctx.strokeStyle = "#ffb216";
      ctx.arc(0, height / 2 + 2 * rotateR, 1.2 * rotateR, 0, 2 * Math.PI);
      ctx.fillStyle = "#ffb216";
      ctx.fill();
      ctx.stroke();
      //旋转控制旋钮
      ctx.drawImage(icon, -rotateR, height / 2 + rotateR, 2 * rotateR, 2 * rotateR)
      // 图形画虚线
      ctx.beginPath();
      ctx.lineWidth = "3";
      ctx.strokeStyle = "#fff";
      ctx.setLineDash([10, 6]);
      ctx.rect(-width / 2 - 3, -height / 2 - 3, width + 6, height + 6);
      ctx.stroke();
      ctx.closePath();
    }
    ctx.draw()
    if (cb) {
      cb()
    }
  },
  convertCoor(P) {//坐标变换 屏幕坐标系的点 转换为canvas坐标系的点
    const { PO } = this.data
    const { rotate_radian } = this.data
    var x = P.x - PO.x;//在屏幕坐标系中，P点相对canvas坐标系原点PO的偏移
    var y = P.y - PO.y;
    if (rotate_radian != 0) {
      var len = Math.sqrt(x * x + y * y);
      var oldR = Math.atan2(y, -x);//屏幕坐标系中 PO与P点连线 与屏幕坐标系X轴的夹角弧度            
      var newR = oldR + rotate_radian;//canvas坐标系中PO与P点连线 与canvas坐标系x轴的夹角弧度
      x = len * Math.cos(newR);
      y = len * Math.sin(newR);
    }
    return { x: x, y: y };
  },
  imgIsDown(x, y) {
    const { imgW, imgH, scale } = this.data
    var width = imgW, height = imgH
    if (scale !== 1) {
      width = width * scale
      height = height * scale
    }
    return (-width / 2 <= x && x <= width / 2 && -height / 2 < y && y <= height / 2);
  },
  RTIsDown(x, y) {
    const { imgH, rotateR, scale } = this.data
    var height = imgH
    if (scale !== 1) {
      height = height * scale
    }
    var round_center = { x: 0, y: height / 2 + 2 * rotateR };
    var bool = this.getPointDistance({ x: x, y: y }, round_center) <= rotateR;
    return bool;
  },
  getPointDistance(a, b) {
    var x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y;
    var dd = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
    return dd;
  },
  bindtouchstart(e) {
    var loc = e.changedTouches[0];//获取鼠标事件在屏幕坐标系的位置（原点在canvas标签左上角）
    var x = loc.x, y = loc.y;
    var cLoc = this.convertCoor(loc);
    var Xc = cLoc.x, Yc = cLoc.y;
    this.setData({
      isDown: true,
      beginX: x,
      beginY: y,
      moveAble: this.imgIsDown(Xc, Yc),
      rotateAble: this.RTIsDown(Xc, Yc),
      logoIsActive: true
    })
  },
  bindtouchmove: throttle((that, e) => {
    const { imgW, imgH, rotate_radian, ctx, isDown, moveAble, rotateAble, beginX, beginY, avatar, PO, cvsW, cvsH } = that.data
    if (isDown == false) return;
    var loc = e.changedTouches[0];
    if (moveAble) {
      var x = loc.x, y = loc.y;
      var dx = x - beginX, dy = y - beginY;
      var mPO = { x: PO.x + dx, y: PO.y + dy };//因为鼠标移动dx dy,所以PO在屏幕坐标系的坐标也 移动dx dy
      ctx.clearRect(-cvsW, -cvsH, 2 * cvsW, 2 * cvsH);
      that.storeAvatar(ctx, avatar, 0, 0, cvsW, cvsH)
      ctx.translate(mPO.x, mPO.y);//canvas坐标系原点移动到新的图片中心点
      if (rotate_radian) {
        ctx.rotate(rotate_radian);
      }
      that.onDraw(true, function () {
        that.setData({
          PO: { //记录下屏幕坐标系上PO的坐标变化
            x: PO.x + dx,
            y: PO.y + dy
          },
          beginX: x, //记录移动后鼠标在屏幕坐标系的新位置   
          beginY: y
        })
      });
    } else if (rotateAble) {
      var cLoc = that.convertCoor(loc);
      var Xc = cLoc.x, Yc = cLoc.y;
      // 在旋转前的canvas坐标系中 move的角度
      // （因为旋钮在上方，所以跟，应该计算 在旋转前canvas坐标系中，鼠标位置和原点连线 与 y轴反方向的夹角）
      var newR = Math.atan2(Xc, Yc);
      // 计算当前点与canvas坐标系原点的距离，以及原点到logo右下角的长度，两个值相比得到缩放倍数
      var len = Math.sqrt(Math.pow(Xc, 2) + Math.pow(Yc, 2))
      var oldLen = Math.sqrt(Math.pow(imgW / 2, 2) + Math.pow(imgH / 2, 2))
      that.setData({
        rotate_radian: rotate_radian + newR,
        scale: len / oldLen // 当前点到y坐标的距离与一半的长度，可以算出缩放比例
      }, () => {
        ctx.clearRect(-cvsW, -cvsH, 2 * cvsW, 2 * cvsH);
        that.storeAvatar(ctx, avatar, 0, 0, cvsW, cvsH)
        ctx.translate(PO.x, PO.y);
        ctx.rotate(rotate_radian + newR);
        that.onDraw(true);
      })
    } else {
      console.log('啥也没有')
    }
  }),
  bindtouchend() {
    this.setData({
      isDown: false,
      moveAble: false,
      rotateAble: false
    })
  },
  saveLogo() {
    const { ctx, cvsW, cvsH, avatar, PO, rotate_radian } = this.data
    this.setData({
      logoIsActive: false
    })
    ctx.clearRect(-cvsW, -cvsH, 2 * cvsW, 2 * cvsH);
    this.storeAvatar(ctx, avatar, 0, 0, cvsW, cvsH)
    ctx.translate(PO.x, PO.y);
    ctx.rotate(rotate_radian);
    this.onDraw(false)
  },
  closeDialog() {
    this.setData({
      showDialog: false
    })
  },
  handleLogoList(data) {
    const list = []
    data.list.forEach(v => {
      list.push({
        ...v,
        bigBg: `${conf.staticDomain}${v.bigBg}?v=${data.imgVersion}`,
        url: `${conf.staticDomain}${v.url}?v=${data.imgVersion}`
      })
    })
    return list
  },
  getSetting(cb) {
    const that = this
    wx.showLoading({ title: '资源请求中......', mask: true });
    if (env === 'release') {
      wx.request({
        url: `${conf.requestDomain}data.json?v=${appData.imgVersion}_${new Date().getFullYear()}_${new Date().getMonth()}_${new Date().getDate()}_${new Date().getHours()}`,
        method: 'GET',
        data: {},
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: res => {
          console.log(res)
          if (res && res.data) {
            const logoList = that.handleLogoList(res.data)
            that.setData({
              logoList
            }, () => {
              wx.hideLoading();
              if (cb) {
                cb()
              }
            })
          }
        },
        fail: err => {
          console.log(err, '出错了')
          wx.showToast({
            icon: 'none',
            title: '资源请求失败，请稍候再试'
          })
          wx.hideLoading();
        }
      })
    } else {
      const logoList = that.handleLogoList(data)
      that.setData({
        logoList
      }, () => {
        wx.hideLoading();
        if (cb) {
          cb()
        }
      })
    }
  },
  onShareAppMessage: function (res) {
    const { staticDomain } = this.data
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '快来生成你的庆祝建党100周年个性头像吧',
      path: '/pages/index/index',
      imageUrl: `${conf.staticDomain}71_logo.png?v=${appData.imgVersion}`
    }
  },
  onShareTimeline: function (res) {
    const { staticDomain } = this.data
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '快来生成你的庆祝建党100周年个性头像吧',
      path: '/pages/index/index',
      imageUrl: `${conf.staticDomain}71_logo.png?v=${appData.imgVersion}`
    }
  },
  onLoad() {
    console.log(data)
    // 初始化canvas
    const that = this
    this.getSetting(function () {
      const ctx = wx.createCanvasContext('myCanvas');
      that.setData({
        ctx
      })
      const query = wx.createSelectorQuery().in(that);
      query.select('#myCanvas').boundingClientRect((rect) => {
        that.setData({
          canvas: rect,
          cvsH: rect.height,
          cvsW: rect.width
        })
        // 判断是否有用户头像
        const userInfo = wx.getStorageSync('userInfo')
        if (userInfo && userInfo !== '{}') {
          that.setData({
            hasUserInfo: true,
            userInfo: JSON.parse(userInfo)
          })
          that.initCanvasFisrt()
        }
      }).exec();
    })


  },
  onShow() {
  },
  onReady() {
  }
})
